import React from 'react';
import { useState, useEffect ,useRef} from 'react';
import './TableData.css';
import { Pagination, ConfigProvider,Modal,Button, Space, Table,message } from 'antd';
import zhCN from 'antd/lib/locale/zh_CN'
import { connect } from 'react-redux';
import { updataCusInfo } from '../../redux/actions/updataAction';
import Service from '../../../../service'


const CusDtata = (props) => {
  // 获取当前登录用户
  const [username,setUsername] = useState("admin")
  useEffect(()=>{
    let userinfo = sessionStorage.getItem("userInfo")
    userinfo = eval("("+userinfo+")")
    setUsername(userinfo.data[0].user_information.account);
  },[])


  const [total,setTotal] = useState(0) // 总条数
  const [page,setPage] = useState(1)  // 设置默认页码
  const [pageSize,setPageSize] = useState(6)
  function changePage(a,b){
    setPage(a)
    setPageSize(b)
  }

  // 获取右边的搜索框
  const HeighSearchObj = useRef({})
  useEffect(()=>{
    if(props.searchText.searchText.length!==0){
      delete HeighSearchObj["phone_number"]
      delete HeighSearchObj["customer_name"]
      var pattern = new RegExp("[0-9]+")
      if(pattern.test(props.searchText.searchText)){  // 数组
        HeighSearchObj.phone_number = props.searchText.searchText
        delete HeighSearchObj.current
        console.log(HeighSearchObj);
        SearchCustomer(HeighSearchObj.customer_name)
      }else{
        HeighSearchObj.customer_name = props.searchText.searchText
        delete HeighSearchObj.current
        console.log(HeighSearchObj.customer_name);
        SearchCustomer(HeighSearchObj.customer_name)
      }
    }else{
      console.log("不搜索");
    }
    
  },[props.searchText.searchText])

   //头部右边搜索框
   const SearchCustomer = async (data)=>{
    let result = await Service.cusManageAll.SearchCustomer(data)
    console.log(result);
  } 

  // 删除客户信息
  const [deleCusName,setDeleCusName] = useState('')

  useEffect(()=>{
    if(props.OneTitleIndex.setOneTitle=== "0"){
      getCustomer(page,pageSize,username)
    }else if(props.OneTitleIndex.setOneTitle==="1"){
      getCustomerToday(page,pageSize,username)
    }else if(props.OneTitleIndex.setOneTitle==="2"){
      getCustomerWeek(page,pageSize,username)
    }else if(props.OneTitleIndex.setOneTitle==="3"){
      getCustomerMonth(page,pageSize,username)
    }
  },[props.OneTitleIndex.setOneTitle,page,pageSize,deleCusName])

  // 客户管理的所有查询
  const getCustomer = async (page,size,username)=>{
    let result = await Service.cusManageAll.customerList(page,size,username)
    let temarr = []
    //  console.log(result.data);
    console.log(result);
    result.data.map(item=>{
      temarr.push({...item,...item.customerContacts[0]});
    })
    setTotal(result.count)
    setItems(temarr)
  } 
  // 客户管理今日新增查询
  const getCustomerToday = async (page,size,username)=>{
    let result = await Service.cusManageAll.customerListToday(page,size,username)
    console.log(result.data);
    let temarr = []
    result.data.map(item=>{
      temarr.push({...item,...item.customerContacts[0]});
    })
    setTotal(result.count)
    setItems(temarr)
  }
  // 客户管理本周新增查询
  const getCustomerWeek = async (page,size,username)=>{
    let result = await Service.cusManageAll.customerListWeek(page,size,username)
    let temarr = []
    result.data.map(item=>{
      temarr.push({...item,...item.customerContacts[0]});
    })
    setTotal(result.count)
    setItems(temarr)
  }
  // 客户管理本月新增查询
  const getCustomerMonth = async (page,size,username)=>{
    let result = await Service.cusManageAll.customerListMonth(page,size,username)
    let temarr = []
    result.data.map(item=>{
      temarr.push({...item,...item.customerContacts[0]});
    })
    setTotal(result.count)
    setItems(temarr)
  }

  // 点击复选框向store发送信息
  function updata(e){
    props.upcusInfo(e)
  }
  
  // 删除客户
  function deleteCus(e){
    setDeleCusName(e.customer_name)
    console.log(deleCusName.length===0);
    showModal()
  }
  // 删除模态框下属
  const [visible, setVisible] = useState(false);
  const showModal = () => {
    setVisible(true);
  };
  const hideModal = () => {
    setVisible(false);
    setDeleCusName('')
  };
  // 删除成功提示框
  const delCusFin = () =>{
    console.log(deleCusName);
    deleteCustomer(deleCusName)
      message.success({
        content:`删除客户${deleCusName}成功`,
        duration:1,
      });
    setDeleCusName('')
    setVisible(false);
  }
  // 删除客户接口
  const deleteCustomer = async (data)=>{
    let result = await Service.cusManageAll.DealetCustomer(data)
    console.log(result);
  }
  // 批量删除
  function mutliDelete(){
    console.log(deleCusName);
    if(deleCusName.length===0){
      message.info({
        content:"请选择删除的客户",
        duration:1,
      });
    }else{
      showModal()
    }
    
  }
  //  表格的选择框
const rowSelection = {
  onChange: (selectedRowKeys, selectedRows) => {
    let temarr = []
    selectedRows.map(item=>{
      temarr.push(item.customer_name)
    });
    setDeleCusName(temarr)
  },
  getCheckboxProps: (record) => ({
    disabled: record.name === 'Disabled User',
    name: record.name,
  }),
};

  // 转移客户
  const [transName,setTransName] = useState('')
 
  // 点击转移按钮
  function transNameToOther(){
    if(deleCusName.length===0){
      message.info({
        content:"请选择待转移的客户",
        duration:1,
      });
    }else if(deleCusName.length>1){
      message.info({
        content:"一次只能选择一个客户进行转移",
        duration:1,
      });
    }else if(transName===''){
      message.info({
        content:"请选择转移客户的接收者",
        duration:1,
      });
    }else{
      let transObj = {}
      transObj.customer_name = deleCusName[0]
      transObj.user_name = transName
      console.log(transObj);
      transCustomer(transObj)
    }
  }
  // 点击转移公海按钮
  function transNameToOcean(){
    if(deleCusName.length===0){
      message.info({
        content:"请选择待转移公海的客户",
        duration:1,
      });
    }else if(deleCusName.length>1){
      message.info({
        content:"一次只能选择一个客户进行转移",
        duration:1,
      })
    }else{
      let transOceanObj = {}
      transOceanObj.customer_name = deleCusName[0]
      console.log(transOceanObj);
      transCustomerToOcean(transOceanObj)
    }
  }

   // 转移客户的接口
   const transCustomer = async (data)=>{
    let result = await Service.cusManageAll.TransfromCustomer(data)
    console.log(result);
    if(result.code===200){
      message.success({
        content:"转移客户成功",
        duration:1,
      });
    }else{
      message.error({
        content:"转移客户失败!",
        duration:1,
      });
    }
  }
   // 转移客户到公海的接口
   const transCustomerToOcean = async (data)=>{
    let result = await Service.cusManageAll.TransfromCustomerToOcean(data)
    console.log(result);
    if(result.code===200){
      message.success({
        content:"转移客户成功",
        duration:1,
      });
    }else{
      message.error({
        content:"转移客户失败!",
        duration:1,
      });
    }
  }

  //表头设置
  const columns = [
    {
      title: '客户名称',
      dataIndex: 'customer_name',
      width: 100,
      render: (text) => <a href='/home/add_income'>{text}</a>,
    },
    {
      title: '联系人',
      dataIndex: 'contact_name',
      width: 100,
    },
    {
      title: '手机号码',
      dataIndex: 'phone_number',
      width: 120,
    },
    {
      title: 'QQ',
      dataIndex: 'qq',
      width: 120,
    },
    {
      title: '客户类型',
      dataIndex: 'customer_type',
      width: 120,
    },
    {
      title: '所在地区',
      dataIndex: 'region',
      width: 150,
    },
    {
      title: '客户来源',
      dataIndex: 'customer_source',
      width: 120,
    },
    {
      title: '备注',
      dataIndex: 'remark',
      width: 120,
    },
    {
      title: '录入时间',
      dataIndex: 'entry_time',
      width: 180,
    },
    {
      title: '业务员',
      dataIndex: 'salesman',
      width: 120,
    },
    {
      title: '管理',
      render: (_, record) => (
        <Space size="middle">
          <div id='TableData_anniu'>
          <Button size="small" className='TableData_dx'>短信</Button>
          <Button size="small" className='TableData_xg' onClick={()=>{updata(record)}}>修改</Button>
          <Button size="small" className='TableData_sc' onClick={()=>{deleteCus(record)}}>删除</Button>  
          </div>
        </Space>
      ),
    },

  ];
  //设置数据
  const [items, setItems] = useState([])

  const [selectionType, setSelectionType] = useState('checkbox');
 
  return (
    <div id='tablecontent'>
      <Table rowSelection={{
          type: selectionType,
          ...rowSelection,
        }} columns={columns} rowKey={record => record.customer_name} dataSource={items} pagination={false} />

      <div id='MyPagination' >
        <div className='leftInfo'>
          <span>你可将选中的信息</span>
          <select name="" id="" value={transName} onChange={(e)=>{setTransName(e.target.value)}}>
            <option value="">请选择</option>
            <option value="超级管理员">超级管理员</option>
          </select>
          <div className='trans' onClick={transNameToOther}>转移</div>
          <div className='delete' onClick={mutliDelete}>批量删除</div>
          <div className='transform' onClick={transNameToOcean}>转入公海</div>
        </div>
        <ConfigProvider locale={zhCN}>
          <Pagination
            total={total}
            showSizeChanger
            showQuickJumper
            size="large"
            defaultPageSize={pageSize}
            showTotal={(total) => `总共 ${total} 条`}
            onChange={changePage}
          />
        </ConfigProvider>
      </div>
      {/* 删除原因 */}
      <Modal
        title={`删除${deleCusName}的原因`}
        visible={visible}
        onOk={delCusFin}
        onCancel={hideModal}
        okText="确认"
        cancelText="取消"
      >
        <textarea name="" id="" cols="70" rows="5"></textarea>
      </Modal>
    </div>
  )
}



export default connect(
  state=>({OneTitleIndex:state.setOneTitleIndex,
          // 获取头部右边search的值
          searchText:state.isShow}),
  {upcusInfo:updataCusInfo}
)(CusDtata)